﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="XmlHelper.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace Common
{
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;

    public class XmlHelper
    {
        public static T Deserialize<T>(string xmlString)
        {
            using (var stringReader = new StringReader(xmlString))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                var xmlReader = new XmlTextReader(stringReader);
                try
                {
                    return (T)xmlSerializer.Deserialize(xmlReader);
                }
                finally
                {
                    xmlReader.Close();
                }
            }
        }

        public static T Deserialize<T>(WebResponse response)
        {
            var responseStream = response.GetResponseStream();

            if (responseStream == null)
            {
                return default(T);
            }

            using (var streamReader = new StreamReader(responseStream, new UTF8Encoding()))
            {
                var responseString = streamReader.ReadToEnd();

                return Deserialize<T>(responseString);
            }
        }

        public static string Serialize<T>(T data)
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            var memoryStream = new MemoryStream();

            string result;

            using (var streamWriter = new StreamWriter(memoryStream, new UTF8Encoding()))
            {
                xmlSerializer.Serialize(streamWriter, data);

                var buffer = memoryStream.ToArray();
                result = Encoding.UTF8.GetString(buffer);
            }

            return result;
        }
    }
}